// lib/views/person_chat_screen.dart
import 'package:chat/controller/group_chat_controller.dart';
import 'package:chat/model/message_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

final GroupChatController controller = Get.find();
final ScrollController scrollController = ScrollController();

class GroupChatScreen extends StatelessWidget {
  const GroupChatScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Obx(
          () => Column(
            children: [
              Text(controller.currentContact.value),
              Text('19 Members', style: TextStyle(fontSize: 12, color: Colors.grey[600])),
            ],
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        foregroundColor: Colors.black,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          PopupMenuButton<String>(
            position: PopupMenuPosition.under,
            color: Colors.white,
            offset: Offset(5, 0),
            icon: Icon(Icons.more_vert, color: Colors.grey),
            itemBuilder:
                (BuildContext context) => <PopupMenuEntry<String>>[
                  PopupMenuItem<String>(value: 'option1', child: Text('选项1')),
                  PopupMenuItem<String>(value: 'option2', child: Text('选项2')),
                  PopupMenuItem<String>(value: 'option3', child: Text('选项3')),
                ],
            onSelected: (String value) {
              // 处理菜单项选择
              switch (value) {
                case 'option1':
                  break;
                case 'option2':
                  break;
                case 'option3':
                  break;
              }
            },
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Obx(
                () => ListView.builder(
                  controller: scrollController,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  itemCount: controller.messages.length,
                  itemBuilder: (context, index) {
                    final message = controller.messages.toList()[index];
                    return _buildMessageBubble(message);
                  },
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  _buildInputButton(Icons.mic, () {}),
                  SizedBox(width: 10),
                  Expanded(
                    child: TextField(
                      controller: controller.messageController,
                      focusNode: controller.textFieldFocusNode,
                      decoration: InputDecoration(
                        hintText: 'Message',
                        hintStyle: TextStyle(fontSize: 14, color: Colors.grey[500]),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none,
                        ),
                        filled: true,
                        fillColor: Color(0xFFF5F6F7),
                        contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 10), // 关键调整
                        isDense: true, // 关键参数，减少内部高度
                      ),
                      style: TextStyle(fontSize: 14), // 可选：调小字体
                      onSubmitted: (_) => controller.sendMessage(),
                    ),
                  ),
                  SizedBox(width: 10),
                  _buildInputButton(Icons.image, () {
                    controller.toggleImg();
                  }),
                  SizedBox(width: 10),
                  _buildInputButton(Icons.add, () {
                    controller.toggleOptions();
                  }),
                ],
              ),
            ),
            Obx(() => controller.showImg.value ? _buildImg() : const SizedBox()),
            Obx(() => controller.showOptions.value ? _buildOptions() : const SizedBox()),
          ],
        ),
      ),
    );
  }

  Widget _buildMessageBubble(Message message) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: message.isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        //crossAxisAlignment: CrossAxisAlignment.end, // 使头像和消息底部对齐
        children: [
          if (!message.isMe) // 对方消息显示头像
            Padding(
              padding: const EdgeInsets.only(right: 8),
              child: CircleAvatar(
                backgroundImage: AssetImage('assets/images/zh-CN-XiaochenNeural.png'),
                radius: 16, // 稍微缩小头像
              ),
            ),
          // 消息内容区域
          Flexible(
            // 关键：使用Flexible确保宽度自适应
            child: Column(
              crossAxisAlignment: message.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  decoration: BoxDecoration(
                    color: message.isMe ? Color(0xFFE1F166) : Color(0xFFF5F6F7),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    message.content,
                    style: const TextStyle(fontSize: 16),
                    softWrap: true,
                  ),
                ),
              ],
            ),
          ),
          if (message.isMe) // 消息是我
            Padding(
              padding: const EdgeInsets.only(left: 8),
              child: CircleAvatar(
                backgroundImage: AssetImage('assets/images/zh-CN-XiaohanNeural.png'),
                radius: 16,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildInputButton(IconData icon, VoidCallback onTap) {
    return Container(
      width: 40,
      height: 40,
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Color(0xFFF5F6F7), shape: BoxShape.circle),
      child: IconButton(icon: Icon(icon, size: 16), onPressed: onTap),
    );
  }

  Widget _buildImg() {
    return Container(
      height: 200,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: SingleChildScrollView(
        child: Wrap(
          spacing: 2.0,
          runSpacing: 2.0,
          alignment: WrapAlignment.start,
          children:
              controller.emojis.map((emoji) {
                return GestureDetector(
                  onTap: () {
                    debugPrint('Selected emoji: $emoji');
                  },
                  child: Container(
                    padding: EdgeInsets.all(2),
                    child: Text(emoji, style: TextStyle(fontSize: 24)),
                  ),
                );
              }).toList(),
        ),
      ),
    );
  }

  Widget _buildOptions() {
    return Container(
      height: 200,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildOptionButton(Icons.photo, '照片', () => controller.sendMedia(MessageType.image)),
              SizedBox(width: 20),
              _buildOptionButton(
                Icons.videocam,
                '小视频',
                () => controller.sendMedia(MessageType.video),
              ),
              SizedBox(width: 20),
              _buildOptionButton(
                Icons.location_on,
                '位置',
                () => controller.sendMedia(MessageType.location),
              ),
              SizedBox(width: 20),
              _buildOptionButton(Icons.call, '语音通话', () {}),
            ],
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildOptionButton(Icons.video_call, '视频通话', () {}),
              SizedBox(width: 20),
              _buildOptionButton(
                Icons.keyboard_voice,
                '语音输入',
                () => controller.sendMedia(MessageType.voice),
              ),
              SizedBox(width: 20),
              SizedBox(width: 70),
              SizedBox(width: 20),
              SizedBox(width: 70),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildOptionButton(IconData icon, String label, VoidCallback onTap) {
    return Column(
      children: [
        Container(
          width: 70,
          height: 70,
          decoration: BoxDecoration(
            color: Color(0xFFF5F6F7),
            borderRadius: BorderRadius.circular(16),
          ),
          child: IconButton(icon: Icon(icon), onPressed: onTap),
        ),
        const SizedBox(height: 4),
        Text(label, style: const TextStyle(fontSize: 10)),
      ],
    );
  }
}
